<?php

namespace app\controller;

use app\consts\ExcelConst;
use app\Request;
use app\service\DepartmentService;
use app\utils\Excel;
use think\facade\Config;

class DepartmentController
{

    public function getList(Request $request)
    {
        $name = $request->post('name');
        $code = $request->post('code');
        $page = $request->post('page');
        $pageSize = $request->post('pageSize');
        $result = DepartmentService::getInstance()->getDepartmentList($name, $code, $page, $pageSize);
        return jsonResponse($result);
    }

    public function getDropdownDepartmentList()
    {
        $result = DepartmentService::getInstance()->getDropdownDepartmentList();
        return jsonResponse($result);
    }

    public function create(Request $request)
    {
        validate([
            'name' => 'require',
            'code' => 'require',
            'pid' => 'require',
        ])->check($request->post());

        $name = $request->post('name');
        $code = $request->post('code');
        $pId = $request->post('pid');

        $result = DepartmentService::getInstance()->createDepartment($name, $code, $pId);
        return jsonResponse($result);
    }

    public function update(Request $request)
    {
        validate([
            'id' => 'require',
            'name' => 'require',
            'code' => 'require',
            'pid' => 'require',
        ])->check($request->post());

        $id = $request->post('id');
        $name = $request->post('name');
        $code = $request->post('code');
        $pId = $request->post('pid');

        $result = DepartmentService::getInstance()->updateDepartment($id, $name, $code, $pId);
        return jsonResponse($result);
    }

    public function delete(Request $request)
    {
        validate([
            'id' => 'require',
        ])->check($request->post());

        $id = $request->post('id');
        $result = DepartmentService::getInstance()->deleteDepartment($id);
        return jsonResponse($result);
    }

    public function export(Request $request)
    {
        $name = $request->post('name');
        $code = $request->post('code');

        $exportData = DepartmentService::getInstance()->getDepartmentData($name, $code);
        $excel = new Excel();

        $excel->setChildrenKey("allChildren")
            ->setLevelFields(['name', 'code'])
            ->setFirstLevelHeaders(['部门名称', '部门编码'])
            ->setOtherLevelHeaders(['下属部门', '下属编码']);
        
        return $excel->exportHierarchicalData($exportData, '部门列表', ExcelConst::FORMAT_XLSX);
    }
}